package com.liu.student.controller;

import com.liu.student.entity.Teacher;
import com.liu.student.entity.Course;
import com.liu.student.entity.Enrollment;
import com.liu.student.service.TeacherService;
import com.liu.student.service.CourseService;
import com.liu.student.service.EnrollmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 教师控制器
 */
@Controller
@RequestMapping("/teacher")
@PreAuthorize("hasAnyRole('TEACHER', 'ADMIN')")
public class TeacherController {

    @Autowired
    private TeacherService teacherService;

    @Autowired
    private CourseService courseService;

    @Autowired
    private EnrollmentService enrollmentService;

    @GetMapping("/dashboard")
    public String dashboard(Model model) {
        Teacher currentTeacher = getCurrentTeacher();
        if (currentTeacher != null) {
            model.addAttribute("teacher", currentTeacher);
            
            // 获取教授的课程数量
            List<Course> courses = courseService.findByTeacherId(currentTeacher.getId());
            model.addAttribute("courseCount", courses.size());
        }
        return "teacher/dashboard";
    }

    @GetMapping("/profile")
    public String profile(Model model) {
        Teacher currentTeacher = getCurrentTeacher();
        model.addAttribute("teacher", currentTeacher);
        return "teacher/profile";
    }

    @PostMapping("/profile/update")
    public String updateProfile(@ModelAttribute Teacher teacher) {
        Teacher currentTeacher = getCurrentTeacher();
        if (currentTeacher != null) {
            teacher.setId(currentTeacher.getId());
            teacher.setUserId(currentTeacher.getUserId());
            teacher.setTeacherNumber(currentTeacher.getTeacherNumber()); // 工号不可修改
            teacherService.update(teacher);
        }
        return "redirect:/teacher/profile";
    }

    @GetMapping("/courses")
    public String myCourses(Model model) {
        Teacher currentTeacher = getCurrentTeacher();
        if (currentTeacher != null) {
            List<Course> courses = courseService.findByTeacherId(currentTeacher.getId());
            model.addAttribute("courses", courses);
        }
        return "teacher/courses";
    }

    @GetMapping("/courses/add")
    public String addCourseForm(Model model) {
        model.addAttribute("course", new Course());
        return "teacher/course-form";
    }

    @PostMapping("/courses")
    public String addCourse(@ModelAttribute Course course) {
        Teacher currentTeacher = getCurrentTeacher();
        if (currentTeacher != null) {
            course.setTeacherId(currentTeacher.getId());
            courseService.save(course);
        }
        return "redirect:/teacher/courses";
    }

    @GetMapping("/courses/edit/{id}")
    public String editCourseForm(@PathVariable Long id, Model model) {
        Course course = courseService.findById(id);
        // 检查是否是当前教师的课程
        Teacher currentTeacher = getCurrentTeacher();
        if (currentTeacher != null && course.getTeacherId().equals(currentTeacher.getId())) {
            model.addAttribute("course", course);
            return "teacher/course-form";
        }
        return "redirect:/teacher/courses";
    }

    @PostMapping("/courses/update")
    public String updateCourse(@ModelAttribute Course course) {
        Teacher currentTeacher = getCurrentTeacher();
        if (currentTeacher != null && course.getTeacherId().equals(currentTeacher.getId())) {
            courseService.update(course);
        }
        return "redirect:/teacher/courses";
    }

    @GetMapping("/courses/delete/{id}")
    public String deleteCourse(@PathVariable Long id) {
        Teacher currentTeacher = getCurrentTeacher();
        if (currentTeacher != null) {
            Course course = courseService.findById(id);
            if (course != null && course.getTeacherId().equals(currentTeacher.getId())) {
                courseService.deleteById(id);
            }
        }
        return "redirect:/teacher/courses";
    }

    @GetMapping("/courses/{courseId}/students")
    public String courseStudents(@PathVariable Long courseId, Model model) {
        Teacher currentTeacher = getCurrentTeacher();
        if (currentTeacher != null) {
            Course course = courseService.findById(courseId);
            if (course != null && course.getTeacherId().equals(currentTeacher.getId())) {
                List<Enrollment> enrollments = enrollmentService.findByCourseId(courseId);
                model.addAttribute("course", course);
                model.addAttribute("enrollments", enrollments);
                return "teacher/course-students";
            }
        }
        return "redirect:/teacher/courses";
    }

    @GetMapping("/courses/{courseId}/students/export")
    public String exportCourseStudents(@PathVariable Long courseId) {
        // 这里可以实现Excel导出功能
        // 暂时重定向到学生列表页面
        return "redirect:/teacher/courses/" + courseId + "/students";
    }

    @GetMapping("/schedule")
    public String schedule(Model model) {
        Teacher currentTeacher = getCurrentTeacher();
        if (currentTeacher != null) {
            List<Course> courses = courseService.findByTeacherId(currentTeacher.getId());
            model.addAttribute("courses", courses);
        }
        return "teacher/schedule";
    }

    private Teacher getCurrentTeacher() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated()) {
            String username = authentication.getName();
            return teacherService.findByUsername(username);
        }
        return null;
    }
}